<template>
  <div class="search-suggestion">
    <van-cell  icon="search" v-for="(sug, index) in suggestions" :key="index" @click="$emit('search', sug)">
      <div slot="title" v-html="hightlight(sug)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search'
import { debounce } from 'lodash'
export default {
  name: '',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestions: [] // 联想建议数据列表
    }
  },
  computed: {},
  watch: {
    searchText: {
      handler: debounce(async function () {
        // 防抖函数
        // clearTimeout(this.timeid)
        // this.timeid = setTimeout(async () => {
        //   const { data } = await getSearchSuggestions(this.searchText)
        //   this.suggestions = data.data.options
        // }, 1000)
        const { data } = await getSearchSuggestions(this.searchText)
        this.suggestions = data.data.options
      }, 1000),
      immediate: true
    }
  },
  mounted () {},
  methods: {
    hightlight (str) {
      // 正则表达式 /中间的内容/
      // 都会当做正则匹配模式字符来对待
      // 错误写法 /this.searchText/gi
      //  RegExp 是正则表达式的构造函数
      //  参数1: 字符串
      //  参数2: 匹配模式
      //  返回值: 正则对象
      return str.replace(new RegExp(this.searchText, 'gi'), `<span style='color: red;'>${this.searchText}</span>`)
    }
  }
}

</script>
<style lang='less' scoped>
</style>
